<template>
  <div class="register">
    <div class="container">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="checkPassword">
          <el-input v-model.number="ruleForm.checkPassword" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)" :style="{ width: '100%' }">
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
const ruleFormRef = ref()

const ruleForm = reactive({
  username: '',
  password: '',
  checkPassword: '',
})

const rules = reactive({
  username: [
    { require: true, message: '用户名不能为空', trigger: 'blur' },
    {
      min: 3,
      max: 10,
      message: '用户名长度必须在3到10之间',
      trigger: 'blur',
    },
  ],
  password: [
    { require: true, message: '密码不能为空', trigger: 'blur' },
    {
      min: 6,
      max: 12,
      message: '密码长度必须在6到12之间',
      trigger: 'blur',
    },
  ],
  checkPassword: [
    { require: true, message: '确认密码不能为空', trigger: 'blur' },
    {
      min: 6,
      max: 12,
      message: '确认密码长度必须在6到12之间',
      trigger: 'blur',
    },
    {
      validator: (value, callback) => {
        if (value !== ruleForm.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!')
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style lang="scss" scoped>
.register {
  width: 100%;
  height: 100%;
  .container {
    width: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
